(function (exports) {

    var $ = null;
    var turnTableBaseInfo = null;
    var curWinnersNum = 0;
    var listItemIdx = 0;
    var times = 0;
    var rounds = 0;
    var itemPerSec = 0.4;
    var itemPerHight = 40;
    var itemOriPosy = 350;

    exports.TurnTableLayer = cc.Layer.extend({
        addListener: function (code, listener) {
            network.addListener(code, listener, this);
        },
        onEnter: function () {
            var that = this;

            cc.Layer.prototype.onEnter.call(this);

            cc.loader.loadTxt(TurnTableCfg.proto, function (err, txt) {
                var protoBuf = dcodeIO.ProtoBuf;
                mProto.builder['LuckyDraw'] = protoBuf.loadProto(txt);
                mProto.initCommonModule('LuckyDraw');
                //获取转盘奖励
                network.send(1009,
                    {userid: gameData.uid + "", gameid: TurnTableCfg.gameid}
                );
                //中奖名单
                network.send(1011,
                    {userid: gameData.uid + "", gameid: TurnTableCfg.gameid}
                );
            });

            //转盘基础信息
            this.addListener(1010, function (data) {
                hideLoading();
                if (data.errCode == 0) {
                    turnTableBaseInfo = data;
                    that.initView(data);
                } else {
                    showAlert(data.errMsg);
                }
            });

            //中奖名单rep
            this.addListener(1012, function (data) {
                hideLoading();
                if (data.errCode == 0) {
                    that.initWinner(data['winners'])
                } else {
                    showAlert(data.errMsg);
                }
            });

            //抽奖
            this.addListener(1014, function (data) {
                hideLoading();
                if (data.errCode == 0) {
                    var goodsInfo = null;
                    var goodsCfg = turnTableBaseInfo['showcfg'];
                    if (data.index && goodsCfg) {
                        for (var i = 0; i < goodsCfg.length; i++) {
                            if (goodsCfg[i].index == data.index) {
                                goodsInfo = goodsCfg[i];
                                break;
                            }
                        }
                    }
                    var goodsArr = [];
                    goodsArr.push(goodsInfo);
                    that.lotteryAni(data.index - 1, function () {
                        var goodsTipsLayer = new ShowGoodsLayer(goodsArr, 1, function () {
                            $('bg.runSp').setRotation(0);
                            network.send(3013, {});
                            TouchUtil.setClickDisable($('bg.btn_lottery'), false);
                        });
                        that.addChild(goodsTipsLayer);
                    });
                } else {
                    showAlert(data.errMsg);
                }
            })
        },

        onExit: function () {
            cc.Layer.prototype.onExit.call(this);
            turnTableBaseInfo = null;
            times = 0;
            rounds = 0;
            listItemIdx = 0;
            curWinnersNum = 0;
            network.removeListenersForTarget(this);
        },

        ctor: function () {
            this._super();
            var self = this;
            loadNodeCCS(res.TurnTableLayer_json, self);
            $ = create$(this.getChildByName("Scene"));
            TouchUtil.setOnclickListener($('bg.btn_lottery'), function () {
                TouchUtil.setClickDisable($('bg.btn_lottery'), true);
                //抽奖类型("coin":金币抽奖,"drawticket":抽奖券抽奖)
                if (!turnTableBaseInfo) {
                    return;
                }
                if (gameData.numOfCards[0] < turnTableBaseInfo['coinlimit']) {
                    var _content = '金币数小于' + turnTableBaseInfo['coinlimit'] + '不能参与抽奖额，请充值';

                    showMessageBox(_content, function () {
                        showWindow('CoinShopWindow', 2);
                    }, null, false, true, true);
                    TouchUtil.setClickDisable($('bg.btn_lottery'), false);
                    return;
                }
                network.send(1013, {
                    userid: gameData.uid + '',
                    gameid: TurnTableCfg.gameid,
                    nickname: encodeURIComponent(gameData.nickname),
                    type: 'coin'
                });
                network.send(3013, {});
            });

            TouchUtil.setOnclickListener($('bg.btn_close'), function () {
                self.parent.removeFromParent(true);
            });
            var cmd = '/' + TurnTableCfg.gameid
                + '/click?uid=' + gameData.uid
                + '&where=luckyTable&time=' + getCurTimestamp();
            var sign = '&sign=' + Crypto.MD5('request:' + cmd);
            var url = 'http://static.yygameapi.com:23456' + cmd + sign;
            // console.log('url====:' + url);
            http.post(url, null, function (data) {
                cc.log('打点成功');
            }, function () {
                cc.log('打点失败');
            }, true);

            $('bg.Light2').runAction(cc.repeatForever(
                cc.sequence(
                    cc.delayTime(0.5),
                    cc.show(),
                    cc.delayTime(0.5),
                    cc.hide()
                )
            ))
            return true;
        },
        initView: function (data) {
            $('bg.desp').setString('金币小于' + data['coinlimit'] + '不能参加抽奖');
            var showcfgData = data['showcfg'];
            if (_.isArray(showcfgData)) {
                for (var i = 1; i <= showcfgData.length; i++) {
                    (function (k) {
                        var rewardCfg = showcfgData[k - 1];
                        downLoadImage(rewardCfg['itemurl'], function (texture) {
                            var sp = new cc.Sprite(texture);
                            $('bg.bg1.cell_' + k).addChild(sp);
                            sp.setPosition($('bg.bg1.cell_' + k + '.pos').getPosition());
                            $('bg.bg1.cell_' + k + '.name').setString(rewardCfg['itemname']);
                            $('bg.bg1.cell_' + k + '.name').setVisible(true);
                        })
                    })(i);
                }
            }
            var consume = data['consume'];
            if (consume['coin']) {
                $('bg.btn_lottery.consume').setString(consume['coin']);
                $('bg.btn_lottery.coin').setVisible(true);
            } else if (consume['roomcard']) {
                $('bg.btn_lottery.consume').setString(consume['roomcard']);
                $('bg.btn_lottery.roomcard').setVisible(true);
            } else if (consume['diamond']) {
                $('bg.btn_lottery.consume').setString(consume['diamond']);
                $('bg.btn_lottery.diamond').setVisible(true);
            } else {
                console.log("不明确的消耗");
            }
            $('bg.btn_lottery.consume').setVisible(true);
        },
        //最多50个
        initWinner: function (winners) {
            var that = this;
            if (winners) {
                var itemsCount = winners.length;
                curWinnersNum = itemsCount;
                var allHeight = itemsCount * 40;
                var itemBg = $('bg.itemBg');
                for (var i = 0; i < itemsCount; i++) {
                    (function (k) {
                        var curLuck = winners[k];
                        var item = $('bg.itemBg.item_' + k);
                        if (!item) {
                            item = duplicateNode($('bg.itemBg.item_0'));
                            item.setName('item_' + k);
                            itemBg.addChild(item);
                            item.setPosition(cc.p(240, itemOriPosy - itemPerHight * k));
                        }
                        $('bg.nickname', item).setString(ellipsisStr(decodeURIComponent(curLuck.nickname), 7));
                        $('bg.msg', item).setString(curLuck.msg);
                    })(i);
                }

                if (itemsCount > 10)
                    that.itemsAni(itemsCount, allHeight);
            }
        },
        itemsAni: function (itemsCount, allHeight) {
            for (var i = 0; i < itemsCount; i++) {
                (function (k) {
                    var cell = $('bg.itemBg').getChildByName('item_' + k);
                    var _moveUp = cc.moveBy(itemPerSec, 0, itemPerHight);
                    var _delay1 = cc.delayTime(itemPerSec);
                    var _callFunc = cc.callFunc(function () {
                        var _posy = cell.getPositionY();
                        if (_posy > 400) {
                            cell.setPositionY(itemOriPosy + itemPerHight - allHeight);
                        }
                    });
                    cell.runAction(cc.repeatForever(cc.sequence(_moveUp, _delay1, _callFunc, _delay1)));
                })(i);
            }
        },
        lotteryAni: function (moreAngles, cb) {
            var perMore = moreAngles;

            var _rotate = cc.rotateBy(5.7, (360 * 5 + perMore * 45));
            var _callback = cc.callFunc(function () {
                $('bg.runSp').runAction(cc.sequence(cc.blink(1, 8)));
            });
            var _callback1 = cc.callFunc(function () {
                if (cb && typeof cb === 'function') {
                    cb();
                }
            });
            var _sequence = cc.sequence(_rotate, _callback, _callback1);
            var action = new cc.EaseSineInOut(_sequence);
            $('bg.runSp').runAction(action);
        },
        // 以下刷新屏蔽
        getUserItem: function () {
            if (curWinnersNum < 10)
                return;
            var item = $('bg.itemBg').getChildByName('item_' + listItemIdx);
            listItemIdx++;

            listItemIdx = listItemIdx % curWinnersNum;
            return item;
        },

        updateItemByIndex: function (index) {
            var self = this;
            var item = self.getUserItem();

            var showCfg = turnTableBaseInfo['showcfg'];
            var _index = 0;
            for (var i = 0; i < showCfg.length; i++) {
                if (showCfg[i]['index'] == index) {
                    _index = i;
                    break;
                }
            }

            $('bg.nickname', item).setString(ellipsisStr(gameData.nickname, 7));
            $('bg.msg', item).setString(showCfg[_index]['itemname']);
        },
    });
})(window);